package com.hanter.downloader;

import java.io.Closeable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 文件名：RandomAccessSource <br/>
 * 描述：随机存储的源
 * 创建时间：2022/02/08 16:27
 *
 * @author wangmingshuo
 * @version 1.0
 */
public abstract class RandomAccessSource implements Closeable {

    public abstract void seek(long pos) throws IOException;

    public abstract void write(byte[] buffer, int off, int len) throws IOException;

    public static RandomAccessSource get(File file) throws FileNotFoundException {
        RandomAccessFile raf = new RandomAccessFile(file, "rwd");
        return new RandomAccessSource() {
            @Override
            public void seek(long pos) throws IOException {
                raf.seek(pos);
            }

            @Override
            public void write(byte[] buffer, int off, int len) throws IOException {
                raf.write(buffer, off, len);
            }

            @Override
            public void close() throws IOException {
                raf.close();
            }
        };
    }

    public static RandomAccessSource get(FileDescriptor fd) {
        final FileOutputStream fos = new FileOutputStream(fd);
        final FileChannel fc = fos.getChannel();
        return new RandomAccessSource() {
            @Override
            public void seek(long pos) throws IOException {
                fc.position(pos);
            }

            @Override
            public void write(byte[] buffer, int off, int len) throws IOException {
                fc.write(ByteBuffer.wrap(buffer, 0, len));
            }

            @Override
            public void close() throws IOException {
                fos.close();
            }
        };
    }
}
